/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package my.hibernate;

import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;

/**
 *
 * @author Manu
 */
public class Helper {

    public static void createRecords(Session session) {
        
        //***We create 2 categories
        
        Book book=new Book();
        book.setTitle("Bienvenue chez les Schtroumpfs");
        book.setSynopsis("Une histoire de Schtroumpfs comme il en existe tant ...");
               
        session.saveOrUpdate(book);
        
        List<BookCategory> categories=new ArrayList<BookCategory>();        
        
        BookCategory category=new BookCategory();
        category.setName("enfants");
        category.setDescription("Des livres pour enfants");
        
        category.getBooks().add(book);
        
        session.saveOrUpdate(category);
        
//        categories.add(category);
        
        category=new BookCategory();
        category.setName("B.D.");
        category.setDescription("Des B.D.");
        
        category.getBooks().add(book);
        
        session.saveOrUpdate(category);
        
//        categories.add(category);
        
                
        book.getCategories().addAll(categories);
        session.saveOrUpdate(book);
    }
    
    public static void createRecords2(Session session) {
        BookCategory category=new BookCategory();
        category.setName("Fiction");
        category.setDescription("Fictive works");
        
        Book book=new Book();
        book.setTitle("I was on the Moon");
        book.setSynopsis("A story of men and moons");
        
        category.getBooks().add(book);
        
        session.saveOrUpdate(category);
    }
    
    public static void deleteRecords(Session session) {
        Query query=session.createQuery("from Book where title LIKE '%Schtroump%'");
        Book book=(Book)query.uniqueResult();
        book.setCategories(null);
        
        session.delete(book);
        
        query=session.createQuery("from BookCategory where name='enfants'");
        BookCategory category=(BookCategory)query.uniqueResult();
        category.setBooks(null);
        session.delete(category);
        
        query=session.createQuery("from BookCategory where name='B.D.'");
        category=(BookCategory)query.uniqueResult();
        category.setBooks(null);
        session.delete(category);
    }
}
